
[dbo].[CalculateDeferralConversionAmount]
CREATE FUNCTION [dbo].[CalculateDeferralConversionAmount]
(@invDate datetime, @amountDeferred decimal(18,4), @totalAmount decimal(18,4), @amountConverted decimal(18,4),
@termsCount int, @termsEffectiveCount int, @termsType int, @termsDuration int, @effectiveDate datetime)
RETURNS decimal(18,4)
AS
BEGIN
DECLARE @amountToConvert decimal(18,4)
DECLARE @amountEligibleForConversion decimal(18,4)
DECLARE @amountPerInterval decimal(18,4)
DECLARE @intervalsPassed int
DECLARE @termsTypeYearly int
DECLARE @termsTypeQuarterly int
DECLARE @termsTypeMonthly int
DECLARE @termsTypeWeekly int
DECLARE @termsTypeDaily int
DECLARE @termsTypeEvent int
DECLARE @monthsPassed int
DECLARE @invDateDay int
DECLARE @effectiveDateDay int
DECLARE @dayAfterEffectiveDate int
DECLARE @decimalPlaces int
IF @amountConverted >= @totalAmount
RETURN 0
IF @termsCount = 0
RETURN 0
SET @termsTypeYearly = 0
SET @termsTypeQuarterly = 1
SET @termsTypeMonthly = 2
SET @termsTypeWeekly = 3
SET @termsTypeDaily = 4
SET @termsTypeEvent = 5
SET @decimalPlaces = 2
SET @amountPerInterval = ROUND(@totalAmount / @termsCount, @decimalPlaces)
IF @termsType = @termsTypeYearly
SET @intervalsPassed = DATEDIFF(Day, @invDate, @effectiveDate) / 365
ELSE IF @termsType = @termsTypeWeekly
SET @intervalsPassed = DATEDIFF(Day, @invDate, @effectiveDate) / 7
ELSE IF @termsType = @termsTypeDaily
SET @intervalsPassed = DATEDIFF(Day, @invDate, @effectiveDate)
ELSE IF @termsType = @termsTypeEvent
SET @intervalsPassed = @termsEffectiveCount
ELSE
BEGIN
SET @invDateDay = DATEPART(day, @invDate)
SET @effectiveDateDay = DATEPART(day, @effectiveDate)
SET @monthsPassed = DATEDIFF(Month, @invDate, @effectiveDate)
IF @effectiveDateDay < @invDateDay
BEGIN
SET @dayAfterEffectiveDate = DATEPART(day, DATEADD(day, 1, @effectiveDate))
IF @dayAfterEffectiveDate > @effectiveDateDay
SET @monthsPassed = @monthsPassed - 1
END
IF @termsType = @termsTypeMonthly
SET @intervalsPassed = @monthsPassed
ELSE IF @termsType = @termsTypeQuarterly
SET @intervalsPassed = @monthsPassed / 3
END
IF @termsType != @termsTypeEvent
SET @intervalsPassed = @intervalsPassed + 1
IF @intervalsPassed >= @termsCount
RETURN @totalAmount - @amountConverted
SET @amountEligibleForConversion = @amountPerInterval * @intervalsPassed
IF @amountEligibleForConversion > @amountDeferred
SET @amountEligibleForConversion = @amountDeferred
IF @amountConverted >= @amountEligibleForConversion
SET @amountToConvert = 0
ELSE
SET @amountToConvert = @amountEligibleForConversion - @amountConverted
RETURN @amountToConvert
END
GO